<?php

/**
 * WSB_Db_Table
 *
 * PHP version 5
 *
 * @copyright  2007 Zephir Software Design AG
 */
class WSB_Db_Table extends Zend_Db_Table_Abstract
{

	const SORT_DELETED = 99999999;

	/**
	 * @var string
	 */
	protected $_order = '';

	/**
	 * @var array
	 */
	protected $_listcols = array();

	/**
	 * @todo: Hier sind dringend Anpassungen notwendig!
	 * @param string $key
	 * @return string
	 */
	public function translate($key)
	{
		static $translate = null;
		if(empty($translate)) {
			$translate = Zend_Registry::get('Zend_Translate');
			$segments = explode('_', get_class($this));
			if(count($segments) > 0) {
				$locale = Zend_Registry::get('Zend_Locale');
				// Neue Version
				$translation = sprintf('%s%s/i18n/tables/%s.%s.csv',
					WSB_MODULES_PATH,
					strtolower($segments[0]), // Modulname
					$this->getName(),
					$locale
				);
				if(is_file($translation)) {
					$translate->addTranslation($translation, $locale);
				}
				// Übergangs-Version
				$translation = sprintf('%s%s/models/table.%s.csv', WSB_XTENSION_PATH, strtolower($segments[0]), $locale);
				if(is_file($translation)) {
					$translate->addTranslation($translation, $locale);
				}
				// Alte Version
				$segments[count($segments)-1] = 'table.'.$locale.'.csv';
				$translation = WSB_PATH . implode('/', $segments);
				if(is_file($translation)) {
					$translate->addTranslation($translation, $locale);
				}
			}
		}
		return $translate->_($key);
	}

	/**
	 * @return string
	 */
	public function getClass()
	{
		return get_class($this);
	}

	/**
	 * @return string
	 */
	public function getName()
	{
		return $this->_name;
	}

	/**
	 * @return string
	 */
	public function getOrder()
	{
		return $this->_order;
	}

	/**
	 * @return array
	 */
	public function getListCols()
	{
		return $this->_listcols;
	}

	/**
	 * @return string
	 */
	public function getPrimary()
	{
		if(is_array($this->_primary)) {
			return reset($this->_primary);
		}
		return $this->_primary;
	}

	/**
	 * @return array
	 */
	public function getReferences()
	{
		$references = array();
		foreach($this->_referenceMap AS $reference) {
			$refTableClass = $reference['refTableClass'];
			$references[$refTableClass] = $this->getReference($refTableClass);
		}
		return $references;
	}

	/**
	 * Is intersection table?
	 *
	 * Es handelt sich um eine Zwischentabelle, wenn es genau
	 * zwei Referenzen gibt.
	 *
	 * @return boolean
	 */
	public function isIntersectionTable()
	{
		$references = $this->getReferences();
		return (count($references) == 2);
	}

	/**
	 * Fetch pairs
	 *
	 * @param string $key
	 * @param string $label
	 * @param string $where
	 * @param string $order
	 * @return array
	 */
	public function fetchPairs($key, $label, $where=null, $order=null)
	{
		$select = $this->_db->select();
		$select->from($this->_name, array($key, $label));
		if(!empty($where)) {
			$select->where($where);
		}
		if(!empty($order)) {
			$select->order($order);
		}
		$result = $this->_db->fetchAll($select);
		$pairs = array();
		foreach($result AS $r) {
            $pairs[$r[$key]] = $r[$label];
		}
		return $pairs;
	}

	/**
	 * Moved or inserted item.
	 *
	 * @param WSB_Db_Row $item
	 */
	public function sortRowsAfterMoving(WSB_Db_Row $item)
	{
		if($this->hasColumn('sorting')) {
			$primary = $this->getPrimary();
			$data = array(
				'sorting' => new Zend_Db_Expr('sorting+1')
			);
			$where = array();
			$where[] = $this->_db->quoteInto('instance_id=?', $item->instance_id);
			$where[] = $this->_db->quoteInto('deleted=?', 0);
			$where[] = $this->_db->quoteInto('sorting>=?', $item->sorting);
			$where[] = $this->_db->quoteInto("$primary<>?", $item->$primary);
			$this->update($data, $where);
			$this->sortRows($item->instance_id);
		}
	}

	/**
	 * Deleted item.
	 *
	 * @param WSB_Db_Row $item
	 */
	public function sortRowsAfterDeletion(WSB_Db_Row $item)
	{
		if($this->hasColumn('sorting')) {
			$data = array(
				'sorting' => new Zend_Db_Expr('sorting-1')
			);
			$where = array();
			$where[] = $this->_db->quoteInto('instance_id=?', $item->instance_id);
			$where[] = $this->_db->quoteInto('deleted=?', 0);
			$where[] = $this->_db->quoteInto('sorting>?', $item->sorting);
			$this->update($data, $where);
			$this->sortRows($item->instance_id);
		}
	}

	/**
	 * @param string $column
	 * @return boolean
	 */
	public function hasColumn($column)
	{
		return array_key_exists($column, $this->_metadata) ? true : false;
	}

	/**
	 * @return boolean
	 */
	private function isSortable()
	{
		return $this->hasColumn('sorting');
	}

	/**
	 * @param integer $instanceId
	 */
	public function sortRows($instanceId)
	{
		if($this->hasColumn('sorting') && is_numeric($instanceId)) {
			$select = $this->select();
			$select->where('instance_id=?', $instanceId);
			$select->where('deleted=?', 0);
			$select->order('sorting ASC');
			$sorting = 0;
			foreach($this->fetchAll($select) AS $item) {
				$item->sorting = $sorting;
				$item->save();
				$sorting++;
			}
		}

	}

	/**
	 * @param string $prefix
	 * @return array
	 */
	public function buildColsForSelect($prefix)
	{
    	$info = $this->info();
	    $cols = array();
    	foreach($info['cols'] AS $col) {
	    	$key = $prefix . '.' . $col;
	    	$cols[$key] = $key;
	    }
	    return $cols;
	}

}

